const { ipcRenderer } = require('electron');

// 仅通过IPC获取端口，不设置默认值
let apiPort = null;
let historyData = null;

// 格式化数字
function formatNumber(num) {
    if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
    }
    return num.toString();
}

// 格式化百分比
function formatPercentage(value, total) {
    if (total === 0) return '0.0%';
    return ((value / total) * 100).toFixed(1) + '%';
}

// 渲染玩家徽标（战力、职业）
function renderBadges(player) {
    const fp = Number(player.fightPoint || 0);
    const prof = player.profession && player.profession !== '未知' ? String(player.profession) : '';
    const baseStyle = 'display:inline-flex;align-items:center;height:18px;line-height:18px;border-radius:9px;font-size:11px;font-weight:700;padding:0 6px;color:#111;vertical-align:middle;';
    let html = '';
    if (fp > 0) html += `<span style="${baseStyle}background:#ffd166;margin-left:6px;">战力 ${fp}</span>`;
    if (prof) html += `<span style="${baseStyle}background:#8fd3fe;margin-left:6px;">${prof}</span>`;
    return html;
}

// 新增：统一API地址生成函数（兼容IPv4/IPv6）
function getApiUrl(endpoint) {
    // 优先使用IPv4地址，避免解析问题
    const ENDPOINTS = [
        `http://127.0.0.1:${apiPort}`,
        `http://[::1]:${apiPort}`
    ];
    const baseUrl = ENDPOINTS[0];
    return baseUrl + endpoint;
}

// 使用原生XMLHttpRequest替代fetch - 增强超时和重试机制
function fetchData(url, retries = 2, timeout = 15000) {
    return new Promise((resolve, reject) => {
        const attemptRequest = (attempt) => {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.timeout = timeout; // 历史数据使用15秒超时

            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const data = JSON.parse(xhr.responseText);
                        resolve(data);
                    } catch (e) {
                        if (attempt < retries) {
                            console.warn(`JSON解析失败，重试 ${attempt + 1}/${retries + 1}`);
                            setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
                        } else {
                            reject(new Error('Invalid JSON response'));
                        }
                    }
                } else {
                    if (attempt < retries) {
                        console.warn(`HTTP ${xhr.status}，重试 ${attempt + 1}/${retries + 1}`);
                        setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
                    } else {
                        reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
                    }
                }
            };

            xhr.onerror = function () {
                if (attempt < retries) {
                    console.warn(`网络错误，重试 ${attempt + 1}/${retries + 1}`);
                    setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
                } else {
                    reject(new Error('Network error'));
                }
            };

            xhr.ontimeout = function () {
                if (attempt < retries) {
                    console.warn(`请求超时，重试 ${attempt + 1}/${retries + 1}`);
                    setTimeout(() => attemptRequest(attempt + 1), 1000 * (attempt + 1));
                } else {
                    reject(new Error('Request timeout'));
                }
            };

            xhr.send();
        };

        attemptRequest(0);
    });
}

// 加载历史数据
async function loadHistoryData(historyId) {
    try {
        console.log('Loading history data for ID:', historyId);

        // 强制检查端口是否已通过IPC获取
        if (!apiPort) {
            showError('端口未通过IPC正确配置，请检查主进程');
            return;
        }

        if (!historyId) {
            showError('历史记录ID为空');
            return;
        }

        // 修改：使用getApiUrl生成请求地址
        const response = await fetchData(getApiUrl(`/api/history/${historyId}`));
        console.log('History API response:', response);

        if (response.code === 0) {
            historyData = response.data;
            console.log('History data loaded:', historyData);
            console.log('Summary data:', historyData.summary);
            console.log('Players data keys:', Object.keys(historyData.players));
            console.log('First player data:', Object.values(historyData.players)[0]);
            renderHistoryDetail();
        } else {
            showError('加载失败: ' + (response.msg || '未知错误'));
        }
    } catch (error) {
        console.error('加载历史数据失败:', error);
        showError('网络错误: ' + error.message);
    }
}

// 显示错误信息
function showError(message) {
    const loading = document.getElementById('loading');
    loading.innerHTML = `<div class="error"> ${message}</div>`;
}

// 渲染历史详情
function renderHistoryDetail() {
    if (!historyData) return;

    console.log('开始渲染渲染历史详情，数据:', historyData);

    const loading = document.getElementById('loading');
    const content = document.getElementById('content');

    // 隐藏加载，显示内容
    loading.style.display = 'none';
    content.style.display = 'block';

    // 更新标题
    document.getElementById('pageTitle').textContent = historyData.displayTime;
    document.getElementById('pageSubtitle').textContent = `战斗ID: ${historyData.id}`;

    console.log('渲染渲染概览数据...');
    // 渲染概览数据
    renderSummary();

    console.log('渲染图表...');
    // 渲染图表
    renderCharts();

    console.log('渲染玩家详情...');
    // 渲染玩家详情
    renderPlayers();

    console.log('历史详情渲染完成');

    // 最终验证所有图表是否正确渲染
    setTimeout(() => {
        console.log('=== 最终验证 ===');
        const containers = ['dpsChart', 'avgDpsChart', 'damageChart', 'healingChart'];
        containers.forEach(id => {
            const container = document.getElementById(id);
            if (container) {
                console.log(`容器 ${id} 最终状态:`, {
                    exists: true,
                    innerHTML: container.innerHTML.substring(0, 100) + '...',
                    children: container.children.length,
                    style: window.getComputedStyle(container).display
                });
            } else {
                console.log(`容器 ${id} 最终状态: 不存在`);
            }
        });
    }, 100);
}

// 渲染概览数据
function renderSummary() {
    console.log('renderSummary 开始');
    const summaryGrid = document.getElementById('summaryGrid');
    if (!summaryGrid) {
        console.error('找不到 summaryGrid 元素');
        return;
    }

    const summary = historyData.summary;
    console.log('概览数据:', summary);

    summaryGrid.innerHTML = `
        <div class="summary-card">
            <div class="summary-value">${summary.totalPlayers}</div>
            <div class="summary-label">参战玩家</div>
        </div>
        <div class="summary-card">
            <div class="summary-value">${formatNumber(summary.totalDamage)}</div>
            <div class="summary-label">总伤害</div>
        </div>
        <div class="summary-card">
            <div class="summary-value">${formatNumber(summary.totalHealing)}</div>
            <div class="summary-label">总治疗</div>
        </div>
        <div class="summary-card">
            <div class="summary-value">${formatNumber(summary.totalTaken)}</div>
            <div class="summary-label">总承伤</div>
        </div>
        <div class="summary-card">
            <div class="summary-value">${summary.totalTime}秒</div>
            <div class="summary-label">战斗时长</div>
        </div>
    `;
    console.log('概览数据渲染完成');

    const totalPlayers = Object.keys(historyData.players || {}).length;
    const totalDamage = historyData.summary.totalDamage || 0;
    const totalHealing = historyData.summary.totalHealing || 0;
    const totalTime = historyData.summary.totalTime || 0;

    summaryGrid.innerHTML = `
        <div class="summary-item"><div class="summary-value">${totalPlayers}</div><div class="summary-label">参战玩家</div></div>
        <div class="summary-item"><div class="summary-value">${formatNumber(totalDamage)}</div><div class="summary-label">总伤害</div></div>
        <div class="summary-item"><div class="summary-value">${formatNumber(totalHealing)}</div><div class="summary-label">总治疗</div></div>
        <div class="summary-item"><div class="summary-value">${totalTime}</div><div class="summary-label">战斗时长</div></div>
        <div class="summary-item" style="grid-column: span 2; display:flex; align-items:center; justify-content:center;">
            <button id="copyTop5PlayersBtn" style="background: rgba(60,60,60,.85); color:#f0f0f0; border:1px solid rgba(128,128,128,.4); padding:6px 12px; border-radius:6px; cursor:pointer;">复制前5玩家伤害占比</button>
        </div>
    `;

    const btn = document.getElementById('copyTop5PlayersBtn');
    if (btn) {
        btn.addEventListener('click', async () => {
            const players = Object.values(historyData.players || {}).sort((a,b)=> (b.total_damage?.total||0) - (a.total_damage?.total||0));
            const total = players.reduce((s,p)=> s + (p.total_damage?.total||0), 0) || 1;
            const top5 = players.slice(0,5);
            const text = top5.map((p,i)=> `#${i+1} ${p.profession||'未知'} ${p.name||p.nickname||('玩家_'+p.uid)} ${((p.total_damage?.total||0)/total*100).toFixed(1)}%`).join('\n') + '\nby_小红猫ACT';
            try { await navigator.clipboard.writeText(text); alert('已复制前5玩家伤害占比'); }
            catch { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove(); alert('已复制前5玩家伤害占比'); }
        });
    }
}

// 渲染图表
function renderCharts() {
    console.log('开始渲染图表，玩家数据:', historyData.players);

    const players = Object.values(historyData.players).sort((a, b) =>
        (b.total_damage?.total || 0) - (a.total_damage?.total || 0)
    );

    console.log('排序后的玩家数据:', players);
    console.log('玩家数据长度:', players.length);

    // DPS排行榜
    console.log('渲染DPS图表...');
    renderDpsChart(players);

    // 秒伤排行榜（综合DPS）
    console.log('渲染秒伤图表...');
    renderAvgDpsChart(players);

    // 伤害占比分布
    console.log('渲染伤害占比图表...');
    console.log('准备渲染伤害图表，总伤害:', historyData.summary.totalDamage);
    renderDamageChart(players);

    // 治疗占比分布
    console.log('渲染治疗占比图表...');
    console.log('准备渲染治疗图表，总治疗:', historyData.summary.totalHealing);
    renderHealingChart(players);

    console.log('所有图表渲染完成');

    // 验证所有图表容器是否存在
    const containers = ['dpsChart', 'avgDpsChart', 'damageChart', 'healingChart'];
    containers.forEach(id => {
        const container = document.getElementById(id);
        console.log(`容器 ${id}:`, container ? '存在' : '不存在', container ? container.innerHTML.length : 'N/A');
        if (container) {
            console.log(`容器 ${id} 的样式:`, window.getComputedStyle(container));
            console.log(`容器 ${id} 的类名:`, container.className);
            console.log(`容器 ${id} 的父元素:`, container.parentElement);
        }
    });
}

// 渲染DPS图表
function renderDpsChart(players) {
    console.log('renderDpsChart 开始，玩家数量:', players.length);
    const dpsChart = document.getElementById('dpsChart');
    if (!dpsChart) {
        console.error('找不到 dpsChart 元素');
        return;
    }

    const maxDps = Math.max(...players.map(p => p.total_dps || 0));
    console.log('最大DPS:', maxDps);

    if (maxDps === 0) {
        dpsChart.innerHTML = '<div class="loading">暂无DPS数据</div>';
        return;
    }

    let html = '';

    const LABEL_WIDTH1 = 220;
    players.slice(0, 10).forEach((player, index) => {
        const dps = player.total_dps || 0;
        const percentage = (dps / maxDps) * 100;
        const color = '#d44646'; // 

        html += `
            <div class="bar-item">
                <div class="bar-label" style="width:${LABEL_WIDTH1}px;text-align:right;">
                    <span style="display:inline-flex;align-items:center;gap:6px;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;vertical-align:middle;justify-content:flex-end;">
                        <span style="max-width:${LABEL_WIDTH1 - 90}px;overflow:hidden;text-overflow:ellipsis;">${player.name}</span>
                        ${renderBadges(player)}
                    </span>
                </div>
                <div class="bar-container">
                    <div class="bar-fill" style="width: ${percentage}%; background-color: ${color};">
                       
                    </div>
                     <div class="bar-value">${dps.toFixed(0)}</div>
                </div>
            </div>
        `;
    });

    dpsChart.innerHTML = html;
    console.log('DPS图表渲染完成，HTML长度:', html.length);
}

// 渲染秒伤排行榜（综合DPS）
function renderAvgDpsChart(players) {
    console.log('renderAvgDpsChart 开始，玩家数量:', players.length);
    const avgDpsChart = document.getElementById('avgDpsChart');
    if (!avgDpsChart) {
        console.error('找不到 avgDpsChart 元素');
        return;
    }

    // 按综合DPS排序（考虑瞬时最大值和平均值）
    const sortedPlayers = [...players].sort((a, b) => {
        const aAvgDps = ((a.total_dps || 0) + (a.realtime_dps_max || 0)) / 2;
        const bAvgDps = ((b.total_dps || 0) + (b.realtime_dps_max || 0)) / 2;
        return bAvgDps - aAvgDps;
    });

    const maxAvgDps = Math.max(...sortedPlayers.map(p => ((p.total_dps || 0) + (p.realtime_dps_max || 0)) / 2));
    console.log('最大平均DPS:', maxAvgDps);

    if (maxAvgDps === 0) {
        avgDpsChart.innerHTML = '<div class="loading">暂无秒伤数据</div>';
        return;
    }

    let html = '';

    const LABEL_WIDTH3 = 220;
    sortedPlayers.slice(0, 10).forEach((player, index) => {
        const avgDps = ((player.total_dps || 0) + (player.realtime_dps_max || 0)) / 2;
        const percentage = (avgDps / maxAvgDps) * 100;
        const color = '#d44646'; // 更暗的颜色

        html += `
            <div class="bar-item">
                <div class="bar-label" style="width:${LABEL_WIDTH3}px;text-align:right;">
                    <span style="display:inline-flex;align-items:center;gap:6px;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;vertical-align:middle;justify-content:flex-end;">
                        <span style="max-width:${LABEL_WIDTH3 - 90}px;overflow:hidden;text-overflow:ellipsis;">${player.name}</span>
                        ${renderBadges(player)}
                    </span>
                </div>
                <div class="bar-container">
                    <div class="bar-fill" style="width: ${percentage}%; background-color: ${color};">
                        
                    </div>
                    <div class="bar-value">${avgDps.toFixed(0)}</div>
                </div>
            </div>
        `;
    });

    avgDpsChart.innerHTML = html;
    console.log('秒伤图表渲染完成，HTML长度:', html.length);
}

// 渲染伤害图表
function renderDamageChart(players) {
    console.log('renderDamageChart 开始，玩家数量:', players.length);
    const damageChart = document.getElementById('damageChart');
    if (!damageChart) {
        console.error('找不到 damageChart 元素');
        return;
    }

    const totalDamage = historyData.summary.totalDamage;
    console.log('总伤害:', totalDamage);

    if (totalDamage === 0) {
        damageChart.innerHTML = '<div class="loading">暂无伤害数据</div>';
        console.log('伤害图表：总伤害为0，显示暂无数据');
        return;
    }

    let html = '';

    const LABEL_WIDTH3 = 220;
    players.slice(0, 10).forEach((player, index) => {
        const damage = player.total_damage?.total || 0;
        const percentage = (damage / totalDamage) * 100;
        const color = '#d44646'; // 更暗的颜色

        html += `
            <div class="bar-item">
                <div class="bar-label" style="width:${LABEL_WIDTH3}px;text-align:right;">
                    <span style="display:inline-flex;align-items:center;gap:6px;max-width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;vertical-align:middle;justify-content:flex-end;">
                        <span style="max-width:${LABEL_WIDTH3 - 90}px;overflow:hidden;text-overflow:ellipsis;">${player.name}</span>
                        ${renderBadges(player)}
                    </span>
                </div>
                <div class="bar-container">
                    <div class="bar-fill" style="width: ${percentage}%; background-color: ${color};">
                        
                    </div>
                    <div class="bar-value">${formatPercentage(damage, totalDamage)}</div>
                </div>
            </div>
        `;
    });

    damageChart.innerHTML = html;
    console.log('伤害图表渲染完成，HTML长度:', html.length);
    console.log('伤害图表HTML内容:', html.substring(0, 200) + '...');
}

// 渲染治疗图表
function renderHealingChart(players) {
    console.log('renderHealingChart 开始，玩家数量:', players.length);
    const healingChart = document.getElementById('healingChart');
    if (!healingChart) {
        console.error('找不到 healingChart 元素');
        return;
    }

    const totalHealing = historyData.summary.totalHealing;
    console.log('总治疗:', totalHealing);

    if (totalHealing === 0) {
        healingChart.innerHTML = '<div class="loading">暂无治疗数据</div>';
        console.log('治疗图表：总治疗为0，显示暂无数据');
        return;
    }

    let html = '';
    const healingPlayers = players.filter(p => (p.total_healing?.total || 0) > 0)
        .sort((a, b) => (b.total_healing?.total || 0) - (a.total_healing?.total || 0));

    console.log('有治疗数据的玩家数量:', healingPlayers.length);
    console.log('治疗玩家数据:', healingPlayers);

    const LABEL_WIDTH4 = 220;
    healingPlayers.slice(0, 10).forEach((player, index) => {
        const healing = player.total_healing?.total || 0;
        const percentage = (healing / totalHealing) * 100;
        const color = index < 3 ? ['#1e7e34', '#228b22', '#2e8b57'][index] : '#228b22'; // 更暗的绿色

        html += `
            <div class="bar-item">
                <div class="bar-label" style="width:${LABEL_WIDTH4}px;text-align:right;">
                    <span style="display:inline-flex;align-items:center;gap:6px;max-width:100%;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;justify-content:flex-end;">
                        <span style="max-width:${LABEL_WIDTH4 - 90}px;overflow:hidden;text-overflow:ellipsis;">${player.name}</span>
                        ${renderBadges(player)}
                    </span>
                </div>
                <div class="bar-container">
                    <div class="bar-fill" style="width: ${percentage}%; background-color: ${color};">
                       
                    </div>
                     <div class="bar-value">${formatPercentage(healing, totalHealing)}</div>
                </div>
            </div>
        `;
    });

    if (html === '') {
        healingChart.innerHTML = '<div class="loading">暂无治疗数据</div>';
        console.log('治疗图表：没有治疗数据，显示暂无数据');
    } else {
        healingChart.innerHTML = html;
        console.log('治疗图表HTML内容:', html.substring(0, 200) + '...');
    }
    console.log('治疗图表渲染完成，HTML长度:', html.length);
}

// 渲染玩家详情
function renderPlayers() {
    console.log('renderPlayers 开始');
    const playersContent = document.getElementById('playersContent');
    if (!playersContent) {
        console.error('找不到 playersContent 元素');
        return;
    }

    const players = Object.values(historyData.players).sort((a, b) =>
        (b.total_damage?.total || 0) - (a.total_damage?.total || 0)
    );
    console.log('玩家数量:', players.length);

    let html = '';
    players.forEach((player, index) => {
        const rank = index + 1;

        html += `
            <div class="player-card" onclick="showPlayerSkillDetails('${player.uid}', '${player.name}')" style="cursor: pointer; transition: background 0.2s ease;">
                <div class="player-header" title="点击查看技能详情">
                    <div class="player-name">${player.name}
                        ${Number(player.fightPoint || 0) > 0 ? `<span style=\"margin-left:8px; padding:2px 6px; font-size:12px; font-weight:700; color:#111; background:#ffd166; border-radius:10px;\">战力 ${player.fightPoint}</span>` : ''}
                        ${player.profession && player.profession !== '未知' ? `<span style=\"margin-left:6px; padding:2px 6px; font-size:12px; font-weight:700; color:#111; background:#8fd3fe; border-radius:10px;\">${player.profession}</span>` : ''}
                    </div>
                    <div class="player-rank">#${rank}</div>
                </div>
                
                <div class="player-stats">
                    <div class="stat-item">
                        <div class="stat-value">${formatNumber(player.total_damage?.total || 0)}</div>
                        <div class="stat-label">总伤害</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${(player.total_dps || 0).toFixed(0)}</div>
                        <div class="stat-label">瞬时伤害</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${formatNumber(player.total_healing?.total || 0)}</div>
                        <div class="stat-label">总治疗</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${(player.total_hps || 0).toFixed(0)}</div>
                        <div class="stat-label">瞬时治疗</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${formatNumber(player.taken_damage || 0)}</div>
                        <div class="stat-label">承受伤害</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${player.critRate || '0.0'}%</div>
                        <div class="stat-label">暴击率</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${player.luckyRate || '0.0'}%</div>
                        <div class="stat-label">幸运率</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value">${(player.realtime_dps_max || 0).toFixed(0)}</div>
                        <div class="stat-label">最大瞬时</div>
                    </div>
                </div>
                
                <!-- 移除底部“点击查看详细技能分析”，统一从卡片头进入 -->
            </div>
        `;
    });

    playersContent.innerHTML = html;
    console.log('玩家详情渲染完成，HTML长度:', html.length);
}

// 切换技能详情显示
async function toggleSkills(uid) {
    const skillsContent = document.getElementById(`skills-${uid}`);
    const skillsTitle = skillsContent.previousElementSibling;

    if (skillsContent.classList.contains('expanded')) {
        skillsContent.classList.remove('expanded');
        skillsTitle.textContent = '🗡️ 技能详情 (点击展开)';
    } else {
        skillsContent.classList.add('expanded');
        skillsTitle.textContent = '🗡️ 技能详情 (点击收起)';

        // 如果还没有加载技能数据，则加载
        if (skillsContent.innerHTML.includes('加载技能数据中')) {
            await loadSkillData(uid, skillsContent);
        }
    }
}

// 加载技能数据
async function loadSkillData(uid, container) {
    try {
        // 强制检查端口
        if (!apiPort) {
            container.innerHTML = '<div class="error">端口未通过IPC正确配置</div>';
            return;
        }

        // 根据当前查看的是治疗/承伤数据来排序技能
        let sortParam = '';
        const healingChart = document.getElementById('healingChart');
        const takenChart = document.getElementById('takenChart'); 
        if (healingChart && !healingChart.innerHTML.includes('暂无治疗数据')) {
            sortParam = '?sort=healing';
        } else if (takenChart && !takenChart.innerHTML.includes('暂无承伤数据')) {
            sortParam = '?sort=taken';
        } else {
            sortParam = '?sort=damage';
        }
        
        // 修改：使用getApiUrl生成请求地址
        const response = await fetchData(getApiUrl(`/api/skill-stats/${uid}${sortParam}`));

        if (response.code === 0 && response.data && response.data.length > 0) {
            renderSkillData(response.data, container);
        } else {
            container.innerHTML = '<div class="loading">暂无技能数据</div>';
        }
    } catch (error) {
        console.error('加载技能数据失败:', error);
        container.innerHTML = '<div class="error">加载技能数据失败</div>';
    }
}

// 渲染技能数据
function renderSkillData(skillData, container) {
    const totalDamage = skillData.reduce((sum, skill) => sum + (skill.total_damage || 0), 0);

    if (totalDamage === 0) {
        container.innerHTML = '<div class="loading">暂无技能数据</div>';
        return;
    }

    let html = '';

    // 添加技能类型图例
    html += '<div class="skill-legend">';
    html += '<span class="legend-item damage">🗡️ 伤害</span>';
    html += '<span class="legend-item healing">💚 治疗</span>';
    html += '<span class="legend-item taken">🛡️ 承伤</span>';
    html += '<span class="legend-item mixed">⚡ 复合</span>';
    html += '</div>';

    // 使用技能图表容器样式，与主界面保持一致
    html += `<div class="skill-chart-container">`;
    skillData.forEach((skill, index) => { // 显示所有技能
        const damage = skill.total_damage || 0;
        const percentage = totalDamage > 0 ? ((damage / totalDamage) * 100).toFixed(1) : '0.0';
        const barWidth = totalDamage > 0 ? ((damage / totalDamage) * 100) : 0;
        const skillType = skill.skill_type || 'damage';
        
        // 根据技能类型确定颜色和图标
        let borderColor = '#c0392b';
        let typeIcon = '🗡️';
        let valueLabel = '伤害';
        
        switch (skillType) {
            case 'healing':
                borderColor = '#2ecc71';
                typeIcon = '💚';
                valueLabel = '治疗';
                break;
            case 'taken':
                borderColor = '#95a5a6';
                typeIcon = '🛡️';
                valueLabel = '承伤';
                break;
            case 'mixed':
                borderColor = '#f39c12';
                typeIcon = '⚡';
                valueLabel = '复合';
                break;
            default:
                borderColor = '#c0392b';
                typeIcon = '🗡️';
                valueLabel = '伤害';
                break;
        }

        const critRate = skill.crit_rate || '0.0';
        const critCount = skill.crit_count || 0;
        const luckyRate = skill.lucky_rate || '0.0';

        html += `
            <div class="skill-chart-item skill-${skillType}">
                <div class="skill-chart-header">
                    <div class="skill-chart-name">
                        <span class="skill-type-icon">${typeIcon}</span>
                        <span class="skill-name-text">${skill.skill_name}</span>
                    </div>
                    <div class="skill-chart-percentage">${percentage}%</div>
                </div>
                <div class="skill-chart-bar-container">
                    <div class="skill-chart-bar" style="width: ${barWidth}%; background: ${borderColor}">
                        ${parseFloat(luckyRate) > 0 ? `<div class="lucky-indicator" title="幸运触发率: ${luckyRate}%">✨${luckyRate}%</div>` : ''}
                    </div>
                </div>
                <div class="skill-chart-stats">
                    <span class="skill-chart-damage ${skillType === 'healing' ? 'healing-value' : ''}" title="${valueLabel}: ${formatNumber(damage)}">${formatNumber(damage)}</span>
                    <span class="skill-chart-count">${skill.count || 0}次</span>
                    <span class="skill-chart-crit" title="暴击: ${critCount}次 / 暴击率: ${critRate}%">
                        ${critRate}%
                        ${parseFloat(critRate) > 0 ? '<span class="crit-indicator">💥</span>' : ''}
                    </span>
                </div>
                ${parseFloat(critRate) > 30 ? '<div class="high-crit-badge">高暴击</div>' : ''}
                ${parseFloat(luckyRate) > 10 ? '<div class="lucky-badge">幸运王</div>' : ''}
            </div>
        `;
    });
    html += `</div>`;

    container.innerHTML = html;
}

// 监听来自主进程的历史数据加载请求
ipcRenderer.on('load-history-data', async (event, historyId) => {
    console.log('Received load-history-data event with ID:', historyId);
    
    // 确保端口已加载
    if (!apiPort) {
        try {
            // 再次尝试获取端口
            await fetchApiPort();
        } catch (error) {
            showError('无法获取端口配置: ' + error.message);
            return;
        }
    }
    
    loadHistoryData(historyId);
});

// 专门用于获取API端口的函数
async function fetchApiPort() {
    return new Promise((resolve, reject) => {
        if (!ipcRenderer) {
            reject(new Error('ipcRenderer不可用'));
            return;
        }

        ipcRenderer.invoke('get-settings')
            .then(overlaySettings => {
                port = overlaySettings.apiPort
                if (port && !isNaN(port) && port > 0 && port <= 65535) {
                    apiPort = port;
                    console.log('成功通过IPC获取API端口:', apiPort);
                    resolve();
                } else {
                    reject(new Error(`获取到无效端口: ${port}`));
                }
            })
            .catch(err => {
                reject(new Error(`IPC通信失败: ${err.message}`));
            });
    });
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', async () => {
    console.log('History detail page loaded');

    // 强制通过IPC获取端口，不设置默认值
    try {
        await fetchApiPort();
        console.log('端口初始化完成:', apiPort);
    } catch (error) {
        showError('端口配置失败: ' + error.message);
        console.error('端口获取失败:', error);
        // 不继续执行，必须获取端口才能继续
        return;
    }

    // 验证所有必需的DOM元素
    const requiredElements = ['dpsChart', 'avgDpsChart', 'damageChart', 'healingChart', 'playersContent', 'summaryGrid'];
    requiredElements.forEach(id => {
        const element = document.getElementById(id);
        console.log(`必需元素 ${id}:`, element ? '存在' : '不存在');
    });

    // 如果URL中有历史ID参数，直接加载
    const urlParams = new URLSearchParams(window.location.search);
    const historyId = urlParams.get('id');
    if (historyId) {
        console.log('Found history id in URL:', historyId);
        loadHistoryData(historyId);
    } else {
        console.log('No history id in URL, waiting for IPC event...');
    }
});

// 显示玩家技能详情（历史记录版本）
async function showPlayerSkillDetails(uid, playerName) {
    try {
        // 检查端口
        if (!apiPort) {
            alert('端口未正确配置，无法加载技能详情');
            return;
        }

        console.log('Loading skills for player:', uid);

        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'skill-modal';
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10000;
        `;

        const content = document.createElement('div');
        content.style.cssText = `
            background: rgba(20, 20, 20, 0.95);
            border-radius: 8px;
            padding: 16px;
            max-width: 800px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            border: 2px solid rgba(128, 128, 128, 0.3);
            backdrop-filter: blur(8px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
        `;

        // 标题 + 复制按钮
        content.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; border-bottom: 2px solid rgba(128, 128, 128, 0.3); padding-bottom: 12px;">
                <h3 style="color: #f0f0f0; margin: 0; font-size: 18px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);"> ${playerName} (UID: ${uid}) 技能详情</h3>
                <div style="display:flex;gap:8px;align-items:center;">
                    <button id="copyTop5DamageBtn" style="background: rgba(60, 60, 60, 0.8); color: #f0f0f0; border: 1px solid rgba(128, 128, 128, 0.4); padding: 6px 10px; border-radius: 4px; cursor: pointer; font-size: 12px;">复制前5伤害占比</button>
                    <button onclick="this.closest('.skill-modal').remove()" style="background: rgba(60, 60, 60, 0.8); color: #f0f0f0; border: 1px solid rgba(128, 128, 128, 0.4); padding: 6px 10px; border-radius: 4px; cursor: pointer; font-size: 14px;">✖️</button>
                </div>
            </div>
            <div id="skillContent" style="color: #f0f0f0; padding: 0;"> 正在加载技能数据...</div>
        `;

        modal.appendChild(content);
        document.body.appendChild(modal);

        // 从历史记录中获取技能数据
        const player = historyData.players[uid];
        if (player && player.skillUsage) {
            const skills = Object.keys(player.skillUsage).map(id => ({ skill_id: id, ...(player.skillUsage[id] || {}) }));
            window.__historySkillCache = window.__historySkillCache || {};
            window.__historySkillCache[uid] = normalizeHistorySkills(skills);
            renderPlayerSkillsFromAPI(filterSkillsForHistory(window.__historySkillCache[uid], 'damage'), uid);
        } else {
            try {
                const resp = await fetchData(getApiUrl(`/api/skill-stats/${uid}?sort=damage`));
                const list = (resp && (resp.data || resp.skills)) ? (resp.data || resp.skills) : [];
                window.__historySkillCache = window.__historySkillCache || {};
                window.__historySkillCache[uid] = normalizeHistorySkills(list);
                renderPlayerSkillsFromAPI(filterSkillsForHistory(window.__historySkillCache[uid], 'damage'), uid);
            } catch (error) {
                document.getElementById('skillContent').innerHTML = '<div style="text-align: center; padding: 40px; color: #e74c3c;">加载技能数据失败</div>';
            }
        }

        // 复制前五伤害占比
        const copyBtn = content.querySelector('#copyTop5DamageBtn');
        if (copyBtn) {
            copyBtn.addEventListener('click', async () => {
                const all = (window.__historySkillCache && window.__historySkillCache[uid]) || [];
                const damageOnly = all.filter(s => s.skill_type !== 'healing' && s.skill_type !== 'taken');
                const total = damageOnly.reduce((s, it) => s + (it.total_damage || 0), 0) || 1;
                damageOnly.sort((a,b)=> (b.total_damage||0) - (a.total_damage||0));
                const top5 = damageOnly.slice(0,5);
                const text = top5.map((s, i)=> `${i+1}# ${s.skill_name} ${(s.total_damage/total*100).toFixed(1)}%`).join(' | ') + ' | by_小红猫ACT';
                try { await navigator.clipboard.writeText(text); } catch {
                    const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove();
                }
                try { await ipcRenderer.invoke('simulate-chat-send'); } catch {}
                alert('已复制前5伤害占比并尝试发送到游戏聊天');
            });
        }

    } catch (error) {
        console.error('显示技能详情失败:', error);
        alert('显示技能详情失败: ' + error.message);
    }
}

// 规范化历史技能条目，统一字段
function normalizeHistorySkills(arr) {
    return (arr || []).map(s => ({
        skill_id: Number(s.skill_id || s.id),
        skill_name: s.skill_name || s.name || (s.skillInfo && s.skillInfo.name) || `技能_${s.skill_id || s.id}`,
        skill_type: (s.skill_type || (s.skillInfo && s.skillInfo.type) || 'damage'),
        total_damage: s.total_damage || (s.stats && (s.stats.total || (s.stats.stats && s.stats.stats.total))) || s.total || 0,
        count: s.count || (s.stats && (s.stats.count && s.stats.count.total)) || 0,
        crit_rate: s.crit_rate,
        lucky_rate: s.lucky_rate
    }));
}

// 根据过滤条件筛选技能（damage/healing）
function filterSkillsForHistory(list, filter) {
    if (!Array.isArray(list)) return [];
    if (filter === 'healing') return list.filter(s => s.skill_type === 'healing');
    if (filter === 'damage') return list.filter(s => s.skill_type !== 'healing' && s.skill_type !== 'taken');
    return list;
}

// 从历史记录渲染技能详情
function renderPlayerSkillsFromHistory(player, uid) {
    const skillContent = document.getElementById('skillContent');
    if (!skillContent) return;

    console.log('渲染历史技能数据for player:', player);

    // 尝试多种可能的数据结构
    const skillUsage = player.skillUsage || player.skills || {};
    console.log('技能使用数据:', skillUsage);

    if (!skillUsage || Object.keys(skillUsage).length === 0) {
        skillContent.innerHTML = '<div style="text-align: center; padding: 40px; color: #95a5a6;">该玩家暂无技能数据</div>';
        return;
    }

    const skills = Object.keys(skillUsage).map(skillId => {
        const skill = skillUsage[skillId];
        console.log(`处理技能 ${skillId}:`, skill);

        // 支持多种数据结构
        let stats, count, skillInfo;

        if (skill.stats) {
            stats = skill.stats.stats || skill.stats;
            count = skill.stats.count || {};
        } else {
            stats = skill;
            count = { total: skill.count || 0, critical: skill.crit_count || 0 };
        }

        skillInfo = skill.skillInfo || skill.info || {
            name: skill.name || skill.skill_name || `技能_${skillId}`,
            type: skill.type || skill.skill_type || 'damage'
        };

        const totalDamage = stats.total || stats.damage || skill.total_damage || 0;
        const totalCount = count.total || skill.count || 0;
        const critCount = count.critical || skill.crit_count || 0;
        const luckyCount = count.lucky || skill.lucky_count || 0;

        return {
            skill_id: parseInt(skillId),
            skill_name: skillInfo.name,
            skill_type: skillInfo.type,
            total_damage: totalDamage,
            count: totalCount,
            crit_count: critCount,
            lucky_count: luckyCount
        };
    });

    // 统一排序：默认按伤害值降序（不再分开展示）
    skills.sort((a, b) => (b.total_damage || 0) - (a.total_damage || 0));

    renderSkillDetails(skills, skillContent);
}

// 从API渲染技能详情
function renderPlayerSkillsFromAPI(skillData, uid) {
    const skillContent = document.getElementById('skillContent');
    if (!skillContent) return;

    renderSkillDetails(skillData, skillContent);
}

// 渲染技能详情
function renderSkillDetails(skills, container) {
    if (!skills || skills.length === 0) {
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #94a3b8;">暂无技能数据</div>';
        return;
    }

    let html = '';

    // 添加技能图表容器 - 支持治疗技能颜色区分
    if (skills && skills.length > 0) {
        // 分别计算总伤害和总治疗量
        const totalDamage = skills.reduce((sum, skill) => sum + (skill.skill_type !== 'healing' ? (skill.total_damage || 0) : 0), 0);
        const totalHealing = skills.reduce((sum, skill) => sum + (skill.skill_type === 'healing' ? (skill.total_damage || 0) : 0), 0);

        // 依据实际显示百分比排序（伤害按 totalDamage，治疗按 totalHealing）
        const calcPct = (s) => {
            const base = (s.skill_type === 'healing') ? totalHealing : totalDamage;
            const val = s.total_damage || 0;
            return base > 0 ? (val / base * 100) : 0;
        };
        const sorted = skills.slice().sort((a, b) => calcPct(b) - calcPct(a));

        html += `<div style="margin: 8px 0; padding: 8px; background: rgba(0, 0, 0, 0.3); border-radius: 6px; border: 1px solid rgba(128, 128, 128, 0.3); backdrop-filter: blur(4px);">`;
        
        sorted.forEach((skill) => {
            // 根据技能类型确定颜色和计算百分比的基准
            const skillType = skill.skill_type || 'damage';
            const skillValue = skill.total_damage || 0;
            
            let percentage, barWidth, borderColor, barColor, valueColor;
            
            if (skillType === 'healing') {
                // 治疗技能：绿色主题，按总治疗量计算百分比
                percentage = totalHealing > 0 ? ((skillValue / totalHealing) * 100).toFixed(1) : '0.0';
                barWidth = totalHealing > 0 ? ((skillValue / totalHealing) * 100) : 0;
                borderColor = 'rgba(46, 204, 113, 0.6)'; // 绿色边框
                barColor = 'linear-gradient(90deg, rgba(46, 204, 113, 0.8), rgb(46, 204, 113))'; // 绿色渐变
                valueColor = '#2ecc71'; // 绿色数值
            } else if (skillType === 'mixed') {
                // 混合技能：橙色主题，按总伤害计算百分比
                percentage = totalDamage > 0 ? ((skillValue / totalDamage) * 100).toFixed(1) : '0.0';
                barWidth = totalDamage > 0 ? ((skillValue / totalDamage) * 100) : 0;
                borderColor = 'rgba(243, 156, 18, 0.6)'; // 橙色边框
                barColor = 'linear-gradient(90deg, rgba(243, 156, 18, 0.8), rgb(243, 156, 18))'; // 橙色渐变
                valueColor = '#f39c12'; // 橙色数值
            } else {
                // 伤害技能：红色主题，按总伤害计算百分比
                percentage = totalDamage > 0 ? ((skillValue / totalDamage) * 100).toFixed(1) : '0.0';
                barWidth = totalDamage > 0 ? ((skillValue / totalDamage) * 100) : 0;
                borderColor = 'rgba(235, 40, 40, 0.6)'; // 红色边框
                barColor = 'linear-gradient(90deg, rgba(235, 40, 40, 0.8), rgb(235, 40, 40))'; // 红色渐变
                valueColor = '#e74c3c'; // 红色数值
            }
            
            html += `
                <div style="margin-bottom: 6px; padding: 6px 8px; background: rgba(40, 40, 40, 0.6); border-radius: 4px; border-left: 2px solid ${borderColor}; transition: all 0.2s ease;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                        <div style="font-weight: 600; color: #f0f0f0; font-size: 12px; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);">${skill.skill_name}</div>
                        <div style="font-weight: 700; color: #ffffff; font-size: 11px; background: rgba(0, 0, 0, 0.6); padding: 2px 6px; border-radius: 4px; border: 1px solid rgba(128, 128, 128, 0.4); text-shadow: 0 1px 1px rgba(0, 0, 0, 0.8);">${percentage}%</div>
                    </div>
                    <div style="height: 6px; background: rgba(0, 0, 0, 0.4); border-radius: 3px; overflow: hidden; margin-bottom: 4px; border: 1px solid rgba(64, 64, 64, 0.6); box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.6);">
                        <div style="height: 100%; border-radius: 3px; transition: width 0.3s ease; background: ${barColor}; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4); width: ${barWidth}%;"></div>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; font-size: 10px;">
                        <span style="font-weight: 600; color: ${valueColor}; font-size: 11px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.6);">${formatNumber(skillValue)}</span>
                        <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(96, 96, 96, 0.6);">${skill.count || 0}次</span>
                        <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(128, 128, 128, 0.6);">暴击率 ${skill.crit_rate || '0.0'}%</span>
                        <span style="color: rgba(180, 180, 180, 0.9); font-size: 10px; background: rgba(0, 0, 0, 0.4); padding: 1px 4px; border-radius: 3px; border: 1px solid rgba(128, 128, 128, 0.6);">幸运率 ${skill.lucky_rate || '0.0'}%</span>
                    </div>
                </div>
            `;
        });
        html += `</div>`;
    }

    container.innerHTML = html;
}

// 全局函数，供HTML调用
window.toggleSkills = toggleSkills;
window.showPlayerSkillDetails = showPlayerSkillDetails;